package com.lancoo.answer.view.fragment.composition.answer;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.ivan.EasyImageSelect;
import com.ivan.easyphotos.models.album.entity.Photo;
import com.lancoo.answer.R;
import com.lancoo.answer.helper.ConfirmDialogHelper;
import com.lancoo.answer.helper.LoadDialogHelper;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.model.eventBean.VideoCallBackEventBean;
import com.lancoo.answer.model.eventBean.VideoEventBean;
import com.lancoo.answer.util.ExamFontSizeAdjustUtils;
import com.lancoo.answer.widget.VideoPlayView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by pengmi on 2021/12/8 14:15
 * Description:
 */
public class CompositionVideoAnswerFragment extends Fragment {

    private static final String TAG = "CompositionVideoAnswerF";
    private View converView;
    private Item item;
    private VideoPlayView videoPlayView;
    private RelativeLayout rl_video;
    private LinearLayout ll_video_choose,ll_video_film;
    private int kindIndex=-1;
    private int queseIndex=-1;
    private int smallQueseIndex=-1;
    private View rl_delete;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        converView=inflater.inflate(R.layout.ev_fragment_composition_answer_type_video,container,false);
        return converView;
    }

    public void setItem(Item item) {
        this.item = item;
    }

    public static Fragment loadFragment(int kindIndex, int queseIndex, int smallQueseIndex){

        CompositionVideoAnswerFragment fragment=new CompositionVideoAnswerFragment();
        Bundle mBundle=new Bundle();
        mBundle.putInt("kindIndex",kindIndex);
        mBundle.putInt("queseIndex",queseIndex);
        mBundle.putInt("smallQueseIndex",smallQueseIndex);
        fragment.setArguments(mBundle);
        return fragment;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        adjustFontSize();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    private void initView(View view){
        if (!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
        kindIndex = getArguments().getInt("kindIndex");
        queseIndex = getArguments().getInt("queseIndex");
        smallQueseIndex = getArguments().getInt("smallQueseIndex");
        List<Type> kindBeanListk = ConstantBean.Companion.getConstantExamBean().getTypeList();
        item = kindBeanListk.get(kindIndex).getQuesList().get(queseIndex)
                .getChildList().get(smallQueseIndex).getItemList().get(0);
        Log.e(TAG,""+new Gson().toJson(item));
        videoPlayView = view.findViewById(R.id.videoPlayView);
        rl_delete = view.findViewById(R.id.rl_delet);
        rl_delete.bringToFront();
        ImageView iv_choose = view.findViewById(R.id.iv_local_video);
        ImageView iv_record= view.findViewById(R.id.iv_film_video);
        rl_video = view.findViewById(R.id.rl_video);
        ll_video_choose = view.findViewById(R.id.ll_video_choose);
        ll_video_film = view.findViewById(R.id.ll_video_film);
        iv_choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLocalVideoAblum();
            }
        });

        iv_record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                filmVideo();
            }
        });

        if (TextUtils.isEmpty(item.getVideoPath())){
            hideVideoView();
        }else {
            Log.e("aaaa","展示videoview"+item.getVideoPath());
            Log.e("aaaa","展示videoview"+item.getVideoDuration());
            Log.e("aaaa","展示videoview"+item.getVideoThumbnail());
            showVideoView(item.getVideoPath(),item.getVideoDuration()*1000,item.getVideoThumbnail());
        }

        rl_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideVideoView();
            }
        });
    }


    private void showLocalVideoAblum(){
        EasyImageSelect.withVideo(getActivity())
                .setNeedCompress(true)
                .setMaxImageNumber(1)
                .setUseCustomCamera(true)
                .setCallBack(new EasyImageSelect.ImageSelectCallBack() {
                    @Override
                    public void onImageSelectResult(List<String> imgList, List<Photo> photos) {
                        for (String path:imgList){
                            Log.e("aaaa","拿到的本地视频路径："+path);
                        }
                        postVideoEvent(imgList,0);
//                        showVideoView(imgList.get(0),1000*10,null);
                        item.setVideoPath(imgList.get(0));
                    }

                    @Override
                    public void onDismiss() {

                    }
                }).openVideoAlbum();
    }


    private void filmVideo(){
        EasyImageSelect.withVideo(getActivity())
                .setNeedCompress(true)
                .setMaxImageNumber(1)
                .setUseCustomCamera(true)
                .setCallBack(new EasyImageSelect.ImageSelectCallBack() {
                    @Override
                    public void onImageSelectResult(List<String> imgList, List<Photo> photos) {
                        for (String path:imgList){
                            Log.e("aaaa","拿到的本地视频路径："+path);
                        }
                        postVideoEvent(imgList,0);
//                        showVideoView(imgList.get(0),1000*10,null);
                        item.setVideoPath(imgList.get(0));
                    }

                    @Override
                    public void onDismiss() {
                    }
                }).filmVideo();
    }


    private List<String> tempList;
    private void postVideoEvent(List<String> paths,int operateType){
        tempList=paths;
        if (operateType !=2){
            dialog = LoadDialogHelper.showLoadDialog(getActivity(),R.string.ev_uploading,false);
        }

        VideoEventBean bean = new VideoEventBean();
        bean.setTypeIndex(kindIndex);
        bean.setQueseIndex(queseIndex);
        bean.setChildIndex(smallQueseIndex);
        bean.setVideoList(paths);
        bean.setOperateType(operateType);
        EventBus.getDefault().post(bean);
    }


    private void hideVideoView(){
        rl_delete.setVisibility(View.GONE);
        videoPlayView.setVisibility(View.GONE);
        videoPlayView.setiVideoClick(null);
        ll_video_film.setVisibility(View.VISIBLE);
        ll_video_choose.setVisibility(View.VISIBLE);
        item.setVideoPath("");
        item.setVideoThumbnail("");
    }

    private void showVideoView(String path,long duration,String thumb){
        rl_delete.setVisibility(View.VISIBLE);
        videoPlayView.setVisibility(View.VISIBLE);
        Log.e("aaa","duration:"+duration);
        Log.e("aaaa","thumb:"+thumb);
        videoPlayView.reFresh(path,false,duration,thumb);
        videoPlayView.setiVideoClick(new VideoPlayView.IVideoClick() {
            @Override
            public void onVideoClick(String url, boolean isPlaying) {
                List<String> paths = new ArrayList<>();
                paths.add(url);
                postVideoEvent(paths,2);
            }

            @Override
            public void onVideoLongClick(String url) {

            }
        });
        ll_video_film.setVisibility(View.GONE);
        ll_video_choose.setVisibility(View.GONE);
    }
    private AlertDialog dialog;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVideoCallbcak(VideoCallBackEventBean eventBean){
        if (dialog!=null){
            dialog.dismiss();
        }
        if (eventBean.isSuccess()){
            if (eventBean.getTypeIndex() == kindIndex && eventBean.getQueseIndex() == queseIndex && eventBean.getChildIndex()== smallQueseIndex){
                if (eventBean.getVideoList()!=null && eventBean.getVideoList().size()>0){
                    Log.e("aaa","音频上传回调："+eventBean.getVideoList().get(0));
                    item.setVideoPath(eventBean.getVideoList().get(0));
                    item.setVideoDuration(eventBean.getDuration());   //不要在这里转换成毫秒，后台给我返回的是秒
                    item.setVideoThumbnail(eventBean.getThumb());
                    showVideoView(eventBean.getVideoList().get(0),eventBean.getDuration()*1000,eventBean.getThumb());
                }else {
                    Log.e("aaa","回传的视频为空");
                }
            }
        }else {
            showVideoUploadFailureDialog();
        }

    }



    /**
     * 重新上传视频文件
     */
    private void showVideoUploadFailureDialog(){
        ConfirmDialogHelper.showConfirmDialog(getContext(), 2,
                getString(R.string.ev_video_upload_failure), getString(R.string.ev_upload_retry),
                getString(R.string.ev_cancel), new ConfirmDialogHelper.ConfirCallBack() {
                    @Override
                    public void onSure() {
                        super.onSure();
                        if(tempList==null||tempList.size()==0){
                            return;
                        }
                        postVideoEvent(tempList,0);
                    }
                });
    }

    public void adjustFontSize(){
        if(converView==null){
            return;
        }
        TextView textView = converView.findViewById(R.id.tv_local_choice);
        TextView tv_video = converView.findViewById(R.id.tv_video);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView,14);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(tv_video,14);

    }
}
